package com.ruoyi.db.controller;


import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isolar.comps.core.utils.lang.StringUtils;
import com.isolar.comps.core.web.domain.ResponseSgic;
import com.isolar.comps.mybatis.exception.DsDbException;
import com.isolar.comps.mybatis.util.JdbcUtils;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.db.common.QueryGenerator;
import com.ruoyi.db.domain.SysDataSource;
import com.ruoyi.db.service.ISysDataSourceService;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 多数据源管理
 */
@Slf4j
@Controller
@RequestMapping("/sys/dataSource")
public class SysDataSourceController extends BaseController{

    @Autowired
    private ISysDataSourceService sysDataSourceService;
    
    private String prefix = "system/source";

    @GetMapping()
    public String source()
    {
        return prefix + "/source";
    }

    /**
     * 查询数据源列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysDataSource sysDataSource)
    {
        startPage();
        List<SysDataSource> list = sysDataSourceService.selectSysDataSourceList(sysDataSource);
        return getDataTable(list);
    }

    /**
     * 导出数据源列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysDataSource sysDataSource)
    {
        List<SysDataSource> list = sysDataSourceService.selectSysDataSourceList(sysDataSource);
        ExcelUtil<SysDataSource> util = new ExcelUtil<SysDataSource>(SysDataSource.class);
        return util.exportExcel(list, "数据源数据");
    }

    /**
     * 新增数据源
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存数据源
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysDataSource sysDataSource)
    {
    	JdbcUtils.validate(sysDataSource.getDbUrl());
        return toAjax(sysDataSourceService.insertSysDataSource(sysDataSource));
    }
    
    /**
     * 修改数据源
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        SysDataSource sysDataSource = sysDataSourceService.selectSysDataSourceById(id);
        mmap.put("sysDataSource", sysDataSource);
        return prefix + "/edit";
    }

    /**
     * 修改保存数据源
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysDataSource sysDataSource)
    {
    	JdbcUtils.validate(sysDataSource.getDbUrl());
        return toAjax(sysDataSourceService.updateSysDataSource(sysDataSource));
    }

    /**
     * 删除数据源
     */
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
    	List<String> idList = Arrays.asList(ids.split(","));
        return toAjax(sysDataSourceService.deleteSysDataSourceByIds(ids));
    }
    
    

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public ResponseSgic<?> delete(@RequestParam(name = "id") String id) {
        return sysDataSourceService.deleteDataSource(id);
    }


    /**
     * 分页列表查询
     *
     * @param sysDataSource
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public ResponseSgic<?> queryPageList( SysDataSource sysDataSource,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req
    ) {
        QueryWrapper<SysDataSource> queryWrapper = QueryGenerator.initQueryWrapper(sysDataSource, req.getParameterMap());
        Page<SysDataSource> page = new Page<>(pageNo, pageSize);
        IPage<SysDataSource> pageList = sysDataSourceService.page(page, queryWrapper);
        return ResponseSgic.success(pageList);
    }

    @GetMapping(value = "/options")
    public ResponseSgic<?> queryOptions(SysDataSource sysDataSource, HttpServletRequest req) {
        QueryWrapper<SysDataSource> queryWrapper = QueryGenerator.initQueryWrapper(sysDataSource, req.getParameterMap());
        List<SysDataSource> pageList = sysDataSourceService.list(queryWrapper);
        JSONArray array = new JSONArray(pageList.size());
        for (SysDataSource item : pageList) {
            JSONObject option = new JSONObject(3);
            option.put("value", item.getCode());
            option.put("label", item.getName());
            option.put("text", item.getName());
            array.add(option);
        }
        return ResponseSgic.success(array);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public ResponseSgic<?> queryById(@RequestParam(name = "id") String id) throws InterruptedException {
        SysDataSource sysDataSource = sysDataSourceService.getById(id);
        //密码解密
        String dbPassword = sysDataSource.getDbPassword();
        if(StringUtils.isNotBlank(dbPassword)){
            String decodedStr = SecureUtil.aes().encryptHex(dbPassword);
            sysDataSource.setDbPassword(decodedStr);
        }
        return ResponseSgic.success(sysDataSource);
    }

}
